﻿//
// Copyright(C) MixModes Inc. 2011
// 

using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Interactivity;
using MixModes.Phone.Synergy.Extensions;
using MixModes.Phone.Synergy.Framework;

namespace MixModes.Phone.Synergy.Behaviors
{
    /// <summary>
    /// Loads the content when user scrolls to the end of the list
    /// </summary>
    public class ScrollLoadBehavior : Behavior<FrameworkElement>
    {
        /// <summary>
        /// Command property
        /// </summary>
        public static DependencyProperty CommandProperty = DependencyProperty.Register("Command",
                                                                                       typeof(Binding),
                                                                                       typeof(ScrollLoadBehavior),
                                                                                       new PropertyMetadata(null, OnCommandChanged));

        /// <summary>
        /// Command parameter property
        /// </summary>
        public static DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter",
                                                                                                typeof(Binding),
                                                                                                typeof(ScrollLoadBehavior),
                                                                                                new PropertyMetadata(null, OnCommandParameterChanged));
        /// <summary>
        /// Initializes a new instance of the <see cref="ScrollLoadBehavior"/> class.
        /// </summary>
        public ScrollLoadBehavior()
        {
            _verticalScrollChange = new ObservableDependencyProperty("VerticalOffset", OnVerticalScroll);
        }

        /// <summary>
        /// Command.
        /// </summary>
        /// <returns>Command</returns>
        public Binding Command
        {
            get
            {
                return GetValue(CommandProperty) as Binding;
            }
            set
            {
                SetValue(CommandProperty, value);
            }
        }

        /// <summary>
        /// Command parameter.
        /// </summary>
        /// <returns>Command parameter</returns>
        public Binding CommandParameter
        {
            get
            {
                return GetValue(CommandParameterProperty) as Binding;
            }
            set
            {
                SetValue(CommandParameterProperty, value);
            }
        }

        /// <summary>
        /// Called after the behavior is attached to an AssociatedObject.
        /// </summary>
        /// <remarks>Override this to hook up functionality to the AssociatedObject.</remarks>
        protected override void OnAttached()
        {
            base.OnAttached();

            _verticalScrollChange.RemoveValueChanged();
            
            _scrollViewer = AssociatedObject.GetFirstChild<ScrollViewer>();

            if (_scrollViewer != null)
            {
                _verticalScrollChange.AddValueChanged(_scrollViewer);
            }
            else
            {
                RoutedEventHandler loadHandler = null;
                loadHandler = (a, b) =>
                                        {
                                            _scrollViewer = AssociatedObject.GetFirstChild<ScrollViewer>();

                                            if (_scrollViewer != null)
                                            {
                                                _verticalScrollChange.AddValueChanged(_scrollViewer);
                                            }

                                            AssociatedObject.Loaded -= loadHandler;
                                        };

                AssociatedObject.Loaded += loadHandler;
            }

            if (Command != null)
            {
                _observableCommandBinding.Attach(Command, AssociatedObject);
            }
        }

        /// <summary>
        /// Called when the behavior is being detached from its AssociatedObject, but before it has actually occurred.
        /// </summary>
        /// <remarks>Override this to unhook functionality from the AssociatedObject.</remarks>
        protected override void OnDetaching()
        {
            base.OnDetaching();

            _verticalScrollChange.RemoveValueChanged();
            _scrollViewer = null;
        }

        /// <summary>
        /// Called when vertical scroll happens
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
        private void OnVerticalScroll(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (_scrollViewer.VerticalOffset >= _scrollViewer.ScrollableHeight)
            {
                ICommand command = _observableCommandBinding.Value as ICommand;
                object parameter = _observableCommandParameterBinding.Value;

                if ((command != null) && (command.CanExecute(parameter)))
                {
                    command.Execute(parameter);
                }
            }
        }

        /// <summary>
        /// Called when command binding has changed
        /// </summary>
        /// <param name="d">The d.</param>
        /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
        private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ScrollLoadBehavior ScrollLoadBehavior = d as ScrollLoadBehavior;

            if (ScrollLoadBehavior == null)
            {
                return;
            }

            ScrollLoadBehavior._observableCommandBinding.Detach();

            if ((e.NewValue != null) && (ScrollLoadBehavior.AssociatedObject != null))
            {
                ScrollLoadBehavior._observableCommandBinding.Attach(ScrollLoadBehavior.Command, ScrollLoadBehavior.AssociatedObject);
            }
        }

        /// <summary>
        /// Called when command parameter binding has changed
        /// </summary>
        /// <param name="d">The d.</param>
        /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
        private static void OnCommandParameterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ScrollLoadBehavior ScrollLoadBehavior = d as ScrollLoadBehavior;

            if (ScrollLoadBehavior == null)
            {
                return;
            }

            ScrollLoadBehavior._observableCommandParameterBinding.Detach();

            if ((e.NewValue != null) && (ScrollLoadBehavior.AssociatedObject != null))
            {
                ScrollLoadBehavior._observableCommandParameterBinding.Attach(ScrollLoadBehavior.Command, ScrollLoadBehavior.AssociatedObject);
            }
        }

        // Private members
        private ScrollViewer _scrollViewer;
        private readonly ObservableDependencyProperty _verticalScrollChange;
        private readonly ObservableBinding _observableCommandBinding = new ObservableBinding();
        private readonly ObservableBinding _observableCommandParameterBinding = new ObservableBinding();
    }
}
